var sysUser = {};
var type = RequestURLParam.getParam("type");
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
var form
    , formSelects
    , tableSelect
    , authtree
    , table
    , fileId
    , layer
    , upload
    , url
    , checked = []
    , names
    , checked1;

let orgMap = new Map();
let ognMap = new Map();
let ognPostMap = new Map();
let loseMap = new Map();

layui.config({
    base: '/static/lib/layuiadmin/modules/'
}).extend({
    authtree_zimi: 'authtree_zimi'
}).use(['layer', 'authtree_zimi', 'form', 'table', 'upload'], function () {
    form = layui.form;
    authtree = layui.authtree_zimi;
    layer = layui.layer;
    table = layui.table;
    upload = layui.upload;


    init_data(type); //初始化数据

    loadFile(); //加载文件

    form.verify({
        loginName: function (value) {
            if (!value || value.length == 0) {
                return '请输入登录名，登录名为必须入力项目。'
            }
        },
        userName: function (value) {
            if (!value || value.length == 0) {
                return '请输入姓名，姓名为必须入力项目。'
            }
        },
        postName: function (value) {
            if (!value || value.length == 0) {
                return '请输入主岗位，主岗位为必须入力项目。'
            }
        },
        userEmail: function (value) {
            if (value.length > 0) {
                var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
                if (!reg.test(value)) {
                    return '请输入有效的email。';
                }
            }
        },

        userPhone: function (value) {
            //确认密码
            if (value.length > 0) {
                if (value.length != 11) {
                    return '请输入正确格式的手机号。'
                } else {
                    var patt1 = new RegExp("^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$");
                    if (!patt1.test(value)) {
                        return '请输入正确格式的手机号。';
                    }
                }
            }
        }
    });

    form.on("submit(save)", function (data) {
        var param = data.field;

        sysUser.loginName = param.loginName;
        sysUser.userName = param.userName;
        sysUser.userPhone = param.userPhone;
        sysUser.userEmail = param.userEmail;
        sysUser.userSex = param.userSex;

        saveUser(sysUser);
    })
});


function init_data(type) {
    document.getElementById('loginName').focus();

    // 判断localStorage里保存着用户信息时
    if (localStorage.user) {
        sysUser = eval("(" + localStorage.user + ")");

        console.log(sysUser);

        localStorage.removeItem('user');

        $(".layui-input").each(function () {
            $(this).val(sysUser[this.id])
        });

        $('input[name=userSex]').each(function (item) {
            if (this.defaultValue == sysUser.userSex) {
                $(this).prop('checked', true);
            }
        })
        form.render();


        // 设置岗位
        if (sysUser.postList.length > 0) {
            // 1)机构名称
            $('#orgName').html(`${sysUser.postList[0].orgName}`);

            // 2)主岗位
            $('#postName').val(`${sysUser.postList[0].orgName}-${sysUser.postList[0].postName}`);
            checked1 = sysUser.postList[0];

            // 3)副岗位
            resetUpostName();
        }

        if ($("#upostId").val() && $("#upostId").val().length > 0) {
            seachUpostName(sysUser.upostId.split(','));
        }

        if (sysUser.fileId > 0) {
            $('#useraddImage').attr('src', `/file/view/${sysUser.fileId}`);
        }
    }
}

function resetUpostName() {
    let upostName = '';
    let upost;
    for (var i = 1; i < sysUser.postList.length; i++) {
        if (i > 1) {
            upostName += ", "
        }
        upostName += `${sysUser.postList[i].orgName}-${sysUser.postList[i].postName}`;
        upost = JSON.stringify(sysUser.postList[i]);
        upost = upost.replace(/"/g, "'");

        ognPostMap.set(`${sysUser.postList[i].orgId}-${sysUser.postList[i].postId}`, upost);
    }
    $('#upostName').val(upostName);
}

/*
* @author: wh
* @description: 加载副岗位
*/
function loadUpost() {
    let checkArr = [];

    for (var i = 1; i < sysUser.postList.length; i++) {
        checkArr.push(sysUser.postList[i].orgId + '-' + sysUser.postList[i].postId);
    }

    var index1 = layer.open({
        type: 1,
        title: '加载副岗位',
        btn: ['确定', '取消'],
        area: ['600px', '500px'],
        content: $('#loadTree'),
        success: function () {
            $.ajax({
                url: '/sys-post-privilege/getOrgAndPost',
                type: 'post',
                dataType: 'json',
                success: function (res) {
                    var trees = formatData(res.data, 'parentId', 'id', 'name', 'choiceFlag');
                    // 如果后台返回的不是树结构，请使用 authtree.listConvert 转换
                    authtree.render('#upostTree', trees, {
                        inputname: 'authids[]',
                        layfilter: 'lay-check-auth',
                        autowidth: true,
                        uncheckedArr: [sysUser.postList[0].orgId + '-' + sysUser.postList[0].postId],
                        checkedArr: checkArr,
                        fgo: 1,
                        flags: [3]
                    });

                    // 点击机构节点事件
                    $('span[state="2"]').on('click', function (res) {
                        let div_auth_status = $(this).parent().parent().parent();
                        let div_child_single = div_auth_status.next("div.auth-child").children("div.auth-single").children("div").children("div.auth-status").children("span").children("span").children("input[type=\"checkbox\"]");
                        let checkBox, checkValue;

                        if (div_child_single && div_child_single.length > 0){
                            checkBox = div_child_single[div_child_single.length - 1];
                            checkValue = JSON.parse(checkBox.defaultValue.replace(/'/g, "\""));

                            if (checkValue.postId > 0) {
                                checkBox = null;
                            }
                        }

                        let currentValue = JSON.parse($(this).attr('value').replace(/'/g, "\""));

                        let obj = ognMap.get(currentValue.ognId);

                        // 点击时岗位为默认岗位
                        postObj = {
                            orgId: currentValue.id
                            ,parentId: currentValue.id
                            ,orgName: currentValue.orgName
                            ,postName: obj.postName
                            ,id:0
                            ,postId:0
                            ,flag:3
                        };

                        let key = `${postObj.orgId}-${postObj.postId}`;
                        let index = ognPostMap.get(key);

                        postObj = JSON.stringify(postObj);
                        postObj = postObj.replace(/"/g, '\'');

                        if (!index) {
                            ognPostMap.set(key, postObj);

                            if (checkBox) {
                                checkBox.checked = true;

                                form.render("checkbox");
                            }
                        } else {
                            ognPostMap.delete(key);

                            if (checkBox) {
                                checkBox.checked = false;

                                form.render("checkbox");
                            }
                        }
                    });

                    authtree.on('change(lay-check-auth)', function (data) {
                        // 获取所有已选中节点
                        let tmpChecked = authtree.getChecked('#upostTree');
                        let checkedMap = new Map();
                        let obj;

                        let index;
                        let key;

                        for (var i = 0; i < tmpChecked.length; i++) {
                            obj = JSON.parse(tmpChecked[i].replace(/'/g, "\""));

                            key = `${obj.orgId}-${obj.postId}`;
                            index = ognPostMap.get(key);

                            if (!index) {
                                checkedMap.set(key, tmpChecked[i]);
                            } else {
                                checkedMap.set(key, index);
                            }
                        }

                        for (let val of ognPostMap) {
                            index = loseMap.get(val[0]);

                            if (index) {
                                checkedMap.set(val[0], val[1]);
                            }
                        }

                        ognPostMap.clear();
                        for (let val of checkedMap) {
                            ognPostMap.set(val[0], val[1]);
                        }

                        checkedMap.clear();
                    });

                    authtree.showDept('#upostTree', 2);

                }
            });
        },
        yes: function (res) {
            let postMap = new Map();

            // 只留下主岗位
            for (var i = sysUser.postList.length - 1; i > 0; i--) {
                postMap.set(`${sysUser.postList[i].orgId}-${sysUser.postList[i].postId}`, sysUser.postList[i]);
                sysUser.postList.splice(i, 1);
            }

            let tmpPost, uTmpPost;
            for (var value of ognPostMap) {
                tmpPost = value[1];
                tmpPost = JSON.parse(tmpPost.replace(/'/g, "\""));
                uTmpPost = postMap.get(`${tmpPost.orgId}-${tmpPost.postId}`);

                if (!uTmpPost) {
                    uTmpPost = new Object();
                    uTmpPost.id = 0;
                    uTmpPost.postId = tmpPost.postId;
                    uTmpPost.postName = tmpPost.postName;
                    uTmpPost.orgId = tmpPost.orgId;

                    tmpPost = orgMap.get(uTmpPost.orgId);
                    uTmpPost.orgName = tmpPost.name;

                    uTmpPost.choiceFlag = false;
                }

                sysUser.postList.push(uTmpPost);
            }

            resetUpostName();
            layer.close(index1);
        },
        btn2: function (res) {
            layer.close(index1);
        },
        end: function (res) {
            layer.close(index1);
        }


    });

}

//加载主岗位
function loadPost() {
    var index1 = layer.open({
        type: 1,
        title: '加载主岗位',
        btn: ['确定', '取消'],
        area: ['600px', '500px'],
        content: $('#loadTree1'),
        success: function () {
            $.ajax({
                url: '/sys-post-privilege/getOrgAndPost',
                type: 'post',
                dataType: 'json',
                success: function (res) {
                    var trees = formatData(res.data, 'parentId', 'id', 'name', 'choiceFlag');
                    // 如果后台返回的不是树结构，请使用 authtree.listConvert 转换
                    authtree.render('#postTree', trees, {
                        inputname: 'authids[]',
                        layfilter: 'lay-check-auth',
                        autowidth: true,
                        checkType: 'radio',
                        uncheckedArr: [],
                        checkedArr: [sysUser.postList[0].orgId + '-' + sysUser.postList[0].postId],
                        fgo: 1,
                        flags: [3]
                    });
                    //调整树中radio框的样式
                    $('span input[type=radio]').parent().parent().css('height','30px');

                    // 点击机构节点事件
                    $('span[state="2"]').on('click', function (res) {
                        let aaa = $("input[type=\"radio\"]").prop("checked", false);
                        form.render("radio");

                        let div_auth_status = $(this).parent().parent().parent();
                        let div_child_single = div_auth_status.next("div.auth-child").children("div.auth-single").children("div").children("div.auth-status").children("span").children("span").children("input[type=\"radio\"]");
                        let checkBox, checkValue;

                        if (div_child_single && div_child_single.length > 0){
                            checkBox = div_child_single[div_child_single.length - 1];
                            checkValue = JSON.parse(checkBox.defaultValue.replace(/'/g, "\""));

                            if (checkValue.postId == 0) {
                                checkBox.checked = true;

                                form.render("radio");
                            }
                        }

                        let currentValue = JSON.parse($(this).attr('value').replace(/'/g, "\""));
                        let obj = ognMap.get(currentValue.ognId);

                        // 点击时岗位为默认岗位
                        postObj = JSON.stringify({
                            orgId: currentValue.id
                            ,parentId: currentValue.id
                            ,orgName: currentValue.orgName
                            ,postName: obj.postName
                            ,id:0
                            ,postId:0
                            ,flag:3
                        });

                        checked1 = postObj;
                    });

                    authtree.on('change(lay-check-auth)', function (data) {
                        // 获取所有已选中节点
                        checked1 = authtree.getChecked('#postTree');
                    });

                    authtree.showDept('#postTree', 2);

                }
            });
        },
        yes: function (res) {
            var value = eval("(" + checked1 + ")");
            sysUser.postList[0].postId = value.postId;
            sysUser.postList[0].postName = value.postName;
            sysUser.postList[0].orgId = value.orgId;
            sysUser.postList[0].orgName = value.orgName;
            sysUser.postList[0].choiceFlag = false;

            for (var i = sysUser.postList.length - 1; i > 0; i--) {
                if (sysUser.postList[i].postId == value.postId) {
                    sysUser.postList.splice(i, 1);
                    break;
                }
            }

            resetUpostName();

            $('#postName').val(`${sysUser.postList[0].orgName}-${sysUser.postList[0].postName}`);
            $('#orgName').html(`${sysUser.postList[0].orgName}`);

            layer.close(index1);
        },
        btn2: function (res) {
            layer.close(index1);
        },
        end: function (res) {
            layer.close(index1);
        }

    });
}


/**
 * 加载文件
 * @param fileId
 */
function loadFile() {
    //执行实例
    var uploadInst = upload.render({
        elem: '#file' //绑定元素
        , url: '/file/upload' //上传接口
        , data: {}
        , before: function (obj) {
            obj.preview(function (index, result) {
                $('#useraddImage').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (data) {
            var url = '/file/view/' + data.id
            sysUser.fileId = data.id;
            $('#useraddImage').attr('src', url);
        }

        , error: function () {
            //请求异常回调
        }
    });
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData(values, pid, id, name, checked) {
    var tree = [],
        item,
        obj,
        tmpObj,
        ognObj;

    // 全局变量赋值
    orgMap.clear();
    ognMap.clear();
    loseMap.clear();

    let postMap = new Map();
    let orgList = [];
    let cateMap = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();

        item.name = values[i][name];
        item.value = JSON.stringify(values[i]).replace(/"/g, "'");
        item.checked = values[i][checked];
        item.list = [];

        switch (values[i].flag) {
            case 1:
                item.name = values[i].orgName;
                cateMap.set(values[i].orgId, item);
                tree.push(item);
                break;
            case 2:
                orgMap.set(values[i][id], item);
                orgList.push(values[i]);

                if (values[i][pid] == 0) {
                    ognMap.set(values[i][id], values[i]);
                }

                break;
            case 3:
                postMap.set(values[i][id], item);
                break;
        }
    }

    // 2)插入默认岗位
    for (var i = 0; i < orgList.length; i++) { // 遍历Array
        obj = orgMap.get(orgList[i][id]);
        ognObj = JSON.parse(obj.value.replace(/'/g, "\""));

        if (!orgList[i].roleId) {
            loseMap.set(`${orgList[i][id]}-0`, 1)
            continue;
        }

        tmpObj = new Object();
        tmpObj.orgId = orgList[i][id];
        tmpObj.parentId = orgList[i][id];
        tmpObj.orgName = ognObj.orgName;

        ognObj = ognMap.get(orgList[i].ognId);
        tmpObj.postName = ognObj.postName;

        tmpObj.id = 0;
        tmpObj.postId = 0;
        tmpObj.flag = 3;

        item = new Object();
        item.name = tmpObj.postName;
        item.value = JSON.stringify(tmpObj).replace(/"/g, "'");
        item.checked = false;
        item.list = [];

        obj.list.push(item);
    }

    // 3)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {

        switch (values[i].flag) {
            case 1:
                break;
            case 2:
                if (values[i][pid] > 0) {
                    obj = orgMap.get(values[i][pid]);
                    obj.list.push(orgMap.get(values[i][id]));
                } else {
                    obj = cateMap.get(values[i].orgCateId);
                    obj.list.push(orgMap.get(values[i][id]));
                }

                break;
            case 3:
                obj = orgMap.get(values[i].orgId);

                if (obj.list.length > 0) {
                    obj.list.splice(obj.list.length - 1, 0, postMap.get(values[i][id]));
                } else {
                    obj.list.push(postMap.get(values[i][id]));
                }

                break;
        }
    }

    // 4)删除没有子项目的list
    removeList(tree, 0);

    return tree;
}

function removeList(list, level) {
    for (var i = list.length - 1; i >= 0; i--) {
        if (list[i].list && list[i].list.length == 0) {
            delete list[i].list;

            if (level == 0) {
                list.splice(i, 1);
            }
        } else {
            removeList(list[i].list, level + 1);
        }
    }
}

/**
 * @author wh
 * @description 数组去重
 * @param array
 * @returns {Array}
 */
function uniq(arr) {

    var hash = [];
    arr.forEach(function (item) {
        if (hash.indexOf(item) == -1) {
            hash.push(item);
        }
    })
    return hash;
}

function seachUpostName(arr) {
    $.ajax({
        url: '/sys-user/searchPostName',
        data: {'arr': arr},
        traditional: true,
        type: 'post',
        success: function (res) {
            $('#upostName').val(res.data.join());
            // console.log(res);
        }
    });
}

function saveUser(data) {
    $.ajax({
        url: '/sys-user/update',
        type: 'post',
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded",
        data: {sysUser: JSON.stringify(data)},
        success: function (res) {
            if (res.code == 0) {
                parent.layer.msg('成功！', {icon: 1, time: 800});
                parent.layer.close(index);
            } else {
                parent.layer.msg(res.msg, {icon: 5, time: 800});
            }
        },
        error: function (res) {
            console.log("失败");
            parent.layer.close(index);
        }
    });
}
